package org.jeecg.modules.tankerRegistration.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RestUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.tankerBlack.entity.TankerBlack;
import org.jeecg.modules.tankerBlack.service.ITankerBlackService;
import org.jeecg.modules.tankerRegistration.entity.ReportDTO;
import org.jeecg.modules.tankerRegistration.entity.TakeDeliveryLedgerVO;
import org.jeecg.modules.tankerRegistration.entity.TankerRegistration;
import org.jeecg.modules.tankerRegistration.service.ITankerRegistrationService;
import org.jeecg.modules.tankerRegistration.util.Base64ToMultipartFile;
import org.jeecg.modules.tankerRules.entity.TankerRules;
import org.jeecg.modules.tankerRules.service.ITankerRulesService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 罐车登记表
 * @Author: jeecg-boot
 * @Date:   2024-07-05
 * @Version: V1.0
 */
@Api(tags="罐车登记表")
@RestController
@RequestMapping("/tankerRegistration/tankerRegistration")
@Slf4j
public class TankerRegistrationController extends JeecgController<TankerRegistration, ITankerRegistrationService> {
	@Autowired
	private ITankerRegistrationService tankerRegistrationService;
	@Autowired
	private ITankerRulesService tankerRulesService;
	@Autowired
	private ISysUserService userService;
	@Autowired
	private ITankerBlackService tankerBlackService;

	@Value("${jeecg.path.upload}")
	private String upLoadPath;
	
	/**
	 * 分页列表查询
	 *
	 * @param tankerRegistration
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "罐车登记表-分页列表查询")
	@ApiOperation(value="罐车登记表-分页列表查询", notes="罐车登记表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(TankerRegistration tankerRegistration,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<TankerRegistration> queryWrapper = QueryGenerator.initQueryWrapper(tankerRegistration, req.getParameterMap());
		queryWrapper.ne("audit_status", 12);
		Page<TankerRegistration> page = new Page<TankerRegistration>(pageNo, pageSize);
		IPage<TankerRegistration> pageList = tankerRegistrationService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @AutoLog(value = "罐车登记表-未检验列表(app)")
	 @ApiOperation(value="罐车登记表-未检验列表(app)", notes="罐车登记表-未检验列表(app)")
	 @GetMapping(value = "/m/unCheckList")
	 public Result<?> unCheckList(TankerRegistration tankerRegistration,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 QueryWrapper<TankerRegistration> queryWrapper = QueryGenerator.initQueryWrapper(tankerRegistration, req.getParameterMap());
		 queryWrapper.eq("audit_status", 2);
		 queryWrapper.eq("entry_status", 2);
		 Page<TankerRegistration> page = new Page<TankerRegistration>(pageNo, pageSize);
		 IPage<TankerRegistration> pageList = tankerRegistrationService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 @AutoLog(value = "罐车登记表-二次未审批列表(app)-品质经理")
	 @ApiOperation(value="罐车登记表-二次未审批列表(app)-品质经理", notes="罐车登记表-二次未审批列表(app)-品质经理")
	 @GetMapping(value = "/m/unSurveyorList1")
	 public Result<?> unSurveyorList1(TankerRegistration tankerRegistration,
								  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								  HttpServletRequest req) {
		 QueryWrapper<TankerRegistration> queryWrapper = QueryGenerator.initQueryWrapper(tankerRegistration, req.getParameterMap());
		 queryWrapper.in("audit_status", 4, 6);
		 queryWrapper.eq("entry_status", 1);
		 Page<TankerRegistration> page = new Page<TankerRegistration>(pageNo, pageSize);
		 IPage<TankerRegistration> pageList = tankerRegistrationService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 @AutoLog(value = "罐车登记表-二次未审批列表(app)-业务经理")
	 @ApiOperation(value="罐车登记表-二次未审批列表(app)-业务经理", notes="罐车登记表-二次未审批列表(app)-业务经理")
	 @GetMapping(value = "/m/unSurveyorList2")
	 public Result<?> unSurveyorList2(TankerRegistration tankerRegistration,
									 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									 HttpServletRequest req) {
		 QueryWrapper<TankerRegistration> queryWrapper = QueryGenerator.initQueryWrapper(tankerRegistration, req.getParameterMap());
		 queryWrapper.in("audit_status", 4, 5);
		 queryWrapper.eq("entry_status", 1);
		 Page<TankerRegistration> page = new Page<TankerRegistration>(pageNo, pageSize);
		 IPage<TankerRegistration> pageList = tankerRegistrationService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	/**
	 *   添加
	 *
	 * @param tankerRegistration
	 * @return
	 */
	@AutoLog(value = "罐车登记表-添加")
	@ApiOperation(value="罐车登记表-添加", notes="罐车登记表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody TankerRegistration tankerRegistration) {
		tankerRegistration.setAuditStatus(1);
		tankerRegistration.setRegisterDate(new Date());
		tankerRegistration.setEntryStatus(1);
		tankerRegistrationService.save(tankerRegistration);
		return Result.OK("添加成功！");
	}

	 @AutoLog(value = "罐车登记表-添加(app)")
	 @ApiOperation(value="罐车登记表-添加(app)", notes="罐车登记表-添加(app)")
	 @PostMapping(value = "/m/add")
	 public Result<?> mAdd(@RequestBody TankerRegistration tankerRegistration) {
		 TankerRegistration byPlateNo = tankerRegistrationService.getLastByPlateNo(tankerRegistration.getPlateNo());
		 if (byPlateNo != null) {
			 Integer auditStatus = byPlateNo.getAuditStatus();
			 if (1 == auditStatus) {
				 tankerRegistrationService.removeById(byPlateNo.getId());
			 }
		 }
		 TankerBlack black = tankerBlackService.getByPlateOrTrailerNo(tankerRegistration.getPlateNo(),
				 tankerRegistration.getTrailerNo());
		 if (black != null && black.getEnable() == 1){
			 tankerRegistration.setAuditStatus(14);
		 } else {
			 tankerRegistration.setAuditStatus(1);
		 }
		 tankerRegistration.setRegisterDate(new Date());
		 tankerRegistration.setEntryStatus(1);
		 String location = tankerRegistration.getLocation();
		 TankerRules tankerRules = tankerRulesService.getByLocation(location);
		 if (tankerRules != null && tankerRules.getCheckEnable()){
			 Integer checkTime = tankerRules.getCheckTime();
			 LambdaQueryWrapper<TankerRegistration> wrapper = Wrappers.lambdaQuery();
			 wrapper.eq(TankerRegistration::getPlateNo, tankerRegistration.getPlateNo());
			 if (checkTime > 0) {//正数：手动设置时间
				 // 使用 Calendar 计算 checkTime 天前的日期
				 Calendar calendar = Calendar.getInstance();
				 calendar.add(Calendar.DAY_OF_MONTH, -checkTime);
				 Date date = calendar.getTime();
				 wrapper.in(TankerRegistration::getAuditStatus, 3, 5, 6, 9);//不合格
				 wrapper.gt(TankerRegistration::getCreateTime, date);
				 // 查询符合条件的记录数
				 int count = tankerRegistrationService.count(wrapper);
				 if (count > 0) {
					 tankerRegistration.setLastUnqualifiedMark(1);
				 }
			 } else if (checkTime == 0){//0：永久
				 wrapper.in(TankerRegistration::getAuditStatus, 3, 5, 6, 9);//不合格
				 int count = tankerRegistrationService.count(wrapper);
				 if (count > 0){
					 tankerRegistration.setLastUnqualifiedMark(1);
				 }
			 } else {//负数：仅限上一次
				 wrapper.eq(TankerRegistration::getEntryStatus, 3);
				 wrapper.orderByDesc(TankerRegistration::getCreateTime);
				 wrapper.last("limit 1");
				 TankerRegistration one = tankerRegistrationService.getOne(wrapper);
				 if (one != null && Arrays.asList(3, 5, 6, 9).contains(one.getAuditStatus())){//不合格
					 tankerRegistration.setLastUnqualifiedMark(1);
				 }
			 }
		 }
		 tankerRegistrationService.save(tankerRegistration);
		 return Result.OK("登记成功！");
	 }

	 /**
	  *   审批
	  *
	  * @param tankerRegistration
	  * @return
	  */
	 @AutoLog(value = "罐车登记表-审批")
	 @ApiOperation(value="罐车登记表-审批", notes="罐车登记表-审批")
	 @PostMapping(value = "/check")
	 public Result<?> check(@RequestBody TankerRegistration tankerRegistration) {
		 TankerRegistration byId = tankerRegistrationService.getById(tankerRegistration.getId());
		 if (byId == null){
			 return Result.error("未找到对应数据");
		 }
		 String remarks = tankerRegistration.getRemarks();
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 byId.setAuditName1(user.getRealname());
		 byId.setAuditStatus(tankerRegistration.getAuditStatus()).setAuditDate(new Date());
		 if (StringUtils.isNotBlank(remarks)){
			 byId.setRemarks(user.getRealname() + " : " + remarks);
		 }
		 tankerRegistrationService.updateById(byId);
		 return Result.OK("操作成功！", null);
	 }

	 @AutoLog(value = "罐车登记表-验证(app)")
	 @ApiOperation(value="罐车登记表-验证(app)", notes="罐车登记表-验证(app)")
	 @PostMapping(value = "/surveyor")
	 public Result<?> surveyor(@RequestBody TankerRegistration tankerRegistration) {
		 TankerRegistration byId = tankerRegistrationService.getById(tankerRegistration.getId());
		 if (byId == null){
			 return Result.error("未找到对应数据");
		 }
		 String remarks = tankerRegistration.getRemarks();
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 if (StringUtils.isNotBlank(remarks)){
			 tankerRegistration.setRemarks(user.getRealname() + " : " + remarks);
		 }
		 List<String> role = userService.getRole(user.getUsername());
		 if (role.size() != 1){
			 return Result.error("当前用户必须有且只有一个角色");
		 }
		 String s = role.get(0);
		 String realname = user.getRealname();
		 switch (s){
			 case "quality_manager":
				 tankerRegistration.setAuditName2(realname);
				 tankerRegistration.setAuditDate(new Date());
				 break;
			 case "business_manager":
				 tankerRegistration.setAuditName3(realname);
				 tankerRegistration.setAuditDate(new Date());
				 break;
			 case "first_surveyor":
				 tankerRegistration.setSurveyorName1(realname);
				 tankerRegistration.setSurveyorDate(new Date());
				 break;
			 case "second_surveyor":
				 tankerRegistration.setSurveyorName2(realname);
				 tankerRegistration.setSurveyorDate(new Date());
				 break;
			 case "lead_sealing":
				 tankerRegistration.setLeadSealingName(realname);
				 break;
		 }
		 tankerRegistrationService.updateById(tankerRegistration);
		 return Result.OK("操作成功！", null);
	 }
	
	/**
	 *  编辑
	 *
	 * @param tankerRegistration
	 * @return
	 */
	@AutoLog(value = "罐车登记表-编辑")
	@ApiOperation(value="罐车登记表-编辑", notes="罐车登记表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody TankerRegistration tankerRegistration) {
		tankerRegistrationService.updateById(tankerRegistration);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "罐车登记表-通过id删除")
	@ApiOperation(value="罐车登记表-通过id删除", notes="罐车登记表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		tankerRegistrationService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "罐车登记表-批量删除")
	@ApiOperation(value="罐车登记表-批量删除", notes="罐车登记表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tankerRegistrationService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "罐车登记表-通过id查询")
	@ApiOperation(value="罐车登记表-通过id查询", notes="罐车登记表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		TankerRegistration tankerRegistration = tankerRegistrationService.getById(id);
		if(tankerRegistration==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(tankerRegistration);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param tankerRegistration
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TankerRegistration tankerRegistration) {
        return super.exportXls(request, tankerRegistration, TankerRegistration.class, "罐车登记表");
    }

	/**
	 * 导出发货台账(提货)
	 *
	 * @param request
	 * @param tankerRegistration
	 */
	@RequestMapping(value = "/getTakeDeliveryLedger")
	public ModelAndView getTakeDeliveryLedger(HttpServletRequest request, TankerRegistration tankerRegistration) {
		QueryWrapper<TankerRegistration> queryWrapper = QueryGenerator.initQueryWrapper(tankerRegistration, request.getParameterMap());
		queryWrapper.notIn("audit_status", 12, 13, 14);
		List<TankerRegistration> pageList = tankerRegistrationService.list(queryWrapper);
		List<TankerRegistration> exportList = null;
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportList = pageList.stream().filter(item -> selectionList.contains(getId(item))).collect(Collectors.toList());
		} else {
			exportList = pageList;
		}
		List<TakeDeliveryLedgerVO> collect = exportList.stream().map(tanker -> {
			TakeDeliveryLedgerVO vo = new TakeDeliveryLedgerVO();
			BeanUtils.copyProperties(tanker, vo);
			return vo;
		}).collect(Collectors.toList());
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "发货台账");
		mv.addObject(NormalExcelConstants.CLASS, TakeDeliveryLedgerVO.class);
		ExportParams exportParams=new ExportParams("散装食用植物油交付装卸运输台账", "导出日期"+DateUtils.formatDate(), "发货台账");
		exportParams.setImageBasePath(upLoadPath);
		mv.addObject(NormalExcelConstants.PARAMS,exportParams);
		mv.addObject(NormalExcelConstants.DATA_LIST, collect);
		return mv;
	}

	/**
	 * 获取对象ID
	 *
	 * @return
	 */
	private String getId(TankerRegistration item) {
		try {
			return PropertyUtils.getProperty(item, "id").toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TankerRegistration.class);
    }

	 @AutoLog(value = "罐车登记表-入场")
	 @ApiOperation(value="罐车登记表-入场", notes="罐车登记表-入场")
	 @PostMapping(value = "/inCar")
	 public Result<?> inCar(@RequestBody TankerRegistration tankerRegistration) {
		 TankerRegistration byId = tankerRegistrationService.getById(tankerRegistration.getId());
		 if (byId == null){
			 return Result.error("未找到对应数据");
		 }
		 byId.setEntryStatus(2);
		 byId.setEntryTime(new Date());
		 tankerRegistrationService.updateById(byId);
		 return Result.OK("入场成功！", null);
	 }

	 @AutoLog(value = "罐车登记表-对外-入场")
	 @ApiOperation(value="罐车登记表-对外-入场", notes="罐车登记表-对外-入场")
	 @PostMapping(value = "/m/inCar")
	 public Result<?> mInCar(@RequestBody TankerRegistration tankerRegistration) {
		 String plateNo = tankerRegistration.getPlateNo();
		 Date entryTime = tankerRegistration.getEntryTime();
		 String entryPic = tankerRegistration.getEntryPic();
		 String location = tankerRegistration.getLocation();
		 LambdaQueryWrapper<TankerRegistration> wrapper = Wrappers.lambdaQuery();
		 wrapper.eq(TankerRegistration::getPlateNo, plateNo);
		 wrapper.eq(TankerRegistration::getLocation, location);
		 wrapper.eq(TankerRegistration::getAuditStatus, 2);
		 wrapper.eq(TankerRegistration::getEntryStatus, 1);
		 wrapper.last("limit 1");
		 TankerRegistration one = tankerRegistrationService.getOne(wrapper);
		 if (one == null) {
			 return Result.error("车辆没有已审核通过的记录,禁止入场");
		 }
		 TankerRules byLocation = tankerRulesService.getByLocation(location);
		 Integer registerTime, auditTime;
		 boolean register, audit;
		 if (byLocation != null) {
			 registerTime = byLocation.getRegisterTime();
			 auditTime = byLocation.getAuditTime();
			 register = byLocation.getRegister();
			 audit = byLocation.getAudit();
		 } else {
			 registerTime = 12;
			 auditTime = 12;
			 register = true;
			 audit = true;
		 }
		 if (register){
			 Date registerDate = one.getRegisterDate();
			 if (isExpire(registerDate, registerTime)) {//是否过期
				 one.setAuditStatus(13);
				 tankerRegistrationService.updateById(one);
				 return Result.error("已超过登记时间" + registerTime + "小时,禁止入场");
			 }
		 }
		 if (audit){
			 Date auditDate = one.getAuditDate();
			 if (isExpire(auditDate, auditTime)) {//是否过期
				 one.setAuditStatus(13);
				 tankerRegistrationService.updateById(one);
				 return Result.error("已超过审核通过时间" + auditTime + "小时,禁止入场");
			 }
		 }
		 if (StringUtils.isBlank(entryPic) && entryTime == null){
			 return Result.OK("允许入场！", null);
		 }
		 String path = convertBase64StrToImage(entryPic);
		 if (StringUtils.isNotBlank(path)){
			 if (entryTime == null){
				 one.setEntryTime(new Date());
			 } else {
				 one.setEntryTime(entryTime);
			 }
			 one.setEntryPic(path);
			 one.setEntryStatus(2);
			 tankerRegistrationService.updateById(one);
		 }
		 return Result.OK("入场成功！", null);
	 }

	 //是否过期
	 private static boolean isExpire(Date registerDate, Integer registerTime) {
		 // 将Date转换为LocalDateTime
		 LocalDateTime registerLocalDateTime = registerDate.toInstant()
				 .atZone(ZoneId.systemDefault())
				 .toLocalDateTime();
		 // 当前时间转换为LocalDateTime
		 LocalDateTime currentTime = LocalDateTime.now();
		 // 将registerDate加上registerTime小时
		 LocalDateTime expirationTime = registerLocalDateTime.plusHours(registerTime);
		 return expirationTime.isBefore(currentTime);
	 }

	 @AutoLog(value = "罐车登记表-出场")
	 @ApiOperation(value="罐车登记表-出场", notes="罐车登记表-出场")
	 @PostMapping(value = "/outCar")
	 public Result<?> outCar(@RequestBody TankerRegistration tankerRegistration) {
		 TankerRegistration byId = tankerRegistrationService.getById(tankerRegistration.getId());
		 if (byId == null){
			 return Result.error("未找到对应数据");
		 }
		 byId.setEntryStatus(3);
		 byId.setExitTime(new Date());
		 tankerRegistrationService.updateById(byId);
		 return Result.OK("出场成功！", null);
	 }

	 @AutoLog(value = "罐车登记表-对外-出场")
	 @ApiOperation(value="罐车登记表-对外-出场", notes="罐车登记表-对外-出场")
	 @PostMapping(value = "/m/outCar")
	 public Result<?> mOutCar(@RequestBody TankerRegistration tankerRegistration) {
		 String plateNo = tankerRegistration.getPlateNo();
		 Date exitTime = tankerRegistration.getExitTime();
		 String exitPic = tankerRegistration.getExitPic();
		 String location = tankerRegistration.getLocation();
		 LambdaQueryWrapper<TankerRegistration> wrapper = Wrappers.lambdaQuery();
		 wrapper.eq(TankerRegistration::getPlateNo, plateNo);
		 wrapper.eq(TankerRegistration::getLocation, location);
		 wrapper.in(TankerRegistration::getAuditStatus, 9, 16);
		 wrapper.eq(TankerRegistration::getEntryStatus, 2);
		 wrapper.orderByDesc(TankerRegistration::getCreateTime);
		 wrapper.last("limit 1");
		 TankerRegistration one = tankerRegistrationService.getOne(wrapper);
		 if (one == null){
			 return Result.error("车辆没有已检斤的记录,禁止出场");
		 }
		 if (exitTime == null){
			 one.setExitTime(new Date());
		 } else {
			 one.setExitTime(exitTime);
		 }
		 String path = convertBase64StrToImage(exitPic);
		 one.setExitPic(path);
		 one.setEntryStatus(3);
		 tankerRegistrationService.updateById(one);
		 return Result.OK("出场成功！", null);
	 }

	 @Value(value = "${jeecg.path.upload}")
	 private String uploadpath;

	 /**
	  * Base64字符串转图片
	  *
	  * @param base64String
	  */
	 public String convertBase64StrToImage(String base64String) {
		 ByteArrayInputStream bais = null;
		 try {
			 //获取图片类型
			 String suffix = "jpg";
			 //获取JDK8里的解码器Base64.Decoder,将base64字符串转为字节数组
			 byte[] bytes = Base64.getDecoder().decode(base64String);
			 //构建字节数组输入流
			 bais = new ByteArrayInputStream(bytes);
			 //通过ImageIO把字节数组输入流转为BufferedImage
			 BufferedImage bufferedImage = ImageIO.read(bais);
			 //构建文件
			 String sp = new SimpleDateFormat("yyyy_MM").format(new Date());
			 sp = sp + File.separator + System.currentTimeMillis() + ".jpg";
			 File imageFile = new File(uploadpath + File.separator + sp);
			 if (!imageFile.exists()) {
				 imageFile.mkdirs();// 创建文件根目录
			 }
			 //写入生成文件
			 ImageIO.write(bufferedImage, suffix, imageFile);
			 return sp;
		 } catch (Exception e) {
			 e.printStackTrace();
		 } finally {
			 try {
				 if (bais != null) {
					 bais.close();
				 }
			 } catch (IOException e) {
				 e.printStackTrace();
			 }
		 }
		 return "";
	 }

	@AutoLog(value = "罐车登记表-保存gps截图")
	@ApiOperation(value="罐车登记表-保存gps截图", notes="罐车登记表-保存gps截图")
	 @PostMapping("/screenshot")
	 public Result<?> screenshot(@RequestBody TankerRegistration tankerRegistration){
		 String screenshot = tankerRegistration.getScreenshot();
		 final String[] base64Array = screenshot.split(",");
		 // base64转为流
		 String dataUir = base64Array[0];
		 String data = base64Array[1];
		 MultipartFile multipartFile = new Base64ToMultipartFile(data, dataUir);
		 String s = uploadLocal(multipartFile, "");
		 tankerRegistration.setScreenshot(s);
		 tankerRegistrationService.updateById(tankerRegistration);
		 return Result.OK("保存成功", null);
	 }

	 @AutoLog(value = "罐车登记表-统计图卡片数据")
	 @ApiOperation(value="罐车登记表-统计图卡片数据", notes="罐车登记表-统计图卡片数据")
	 @PostMapping(value = "/reportCard")
	 public Result<?> reportCard(@RequestBody ReportDTO reportDTO) {
		 String startTime = reportDTO.getStartTime();
		 String endTime = reportDTO.getEndTime();
		 QueryWrapper<TankerRegistration> wrapper = Wrappers.query();
		 wrapper.select("COUNT(*) AS total, COUNT(DISTINCT plate_no) AS totalUnique");
		 wrapper.in("audit_status", 2, 7, 8, 11);
		 wrapper.ge(StringUtils.isNotBlank(startTime), "create_time", startTime);
		 wrapper.le(StringUtils.isNotBlank(endTime), "create_time", endTime);
		 List<Map<String, Object>> maps = tankerRegistrationService.listMaps(wrapper);
		 wrapper.clear();
		 wrapper.select("COUNT(*) AS noPassTotal, COUNT(DISTINCT plate_no) AS noPassUnique");
		 wrapper.eq("audit_status", 3);
		 wrapper.ge(StringUtils.isNotBlank(startTime), "create_time", startTime);
		 wrapper.le(StringUtils.isNotBlank(endTime), "create_time", endTime);
		 List<Map<String, Object>> noPass = tankerRegistrationService.listMaps(wrapper);
		 maps.addAll(noPass);
		 wrapper.clear();
		 wrapper.select("COUNT(*) AS unqualifiedTotal, COUNT(DISTINCT plate_no) AS unqualifiedUnique");
		 wrapper.eq("audit_status", 9);
		 wrapper.ge(StringUtils.isNotBlank(startTime), "create_time", startTime);
		 wrapper.le(StringUtils.isNotBlank(endTime), "create_time", endTime);
		 List<Map<String, Object>> unqualified = tankerRegistrationService.listMaps(wrapper);
		 maps.addAll(unqualified);
		 return Result.OK(maps);
	 }

	 @AutoLog(value = "罐车登记表-柱状图")
	 @ApiOperation(value="罐车登记表-柱状图", notes="罐车登记表-柱状图")
	 @PostMapping(value = "/reportBarQualified")
	 public Result<?> reportBarQualified(@RequestBody ReportDTO reportDTO) {
		 String startTime = reportDTO.getStartTime();
		 String endTime = reportDTO.getEndTime();
		 QueryWrapper<TankerRegistration> wrapper = Wrappers.query();
		 wrapper.select("CONCAT(YEAR(create_time), '-', LPAD(MONTH(create_time), 2, '0')) AS month",
				 "SUM(CASE WHEN audit_status IN (2, 7, 8, 11) THEN 1 ELSE 0 END) AS qualifiedCount",
				 "COUNT(DISTINCT CASE WHEN audit_status IN (2, 7, 8, 11) THEN plate_no END) AS qualifiedDistinct");
		 wrapper.ge(StringUtils.isNotBlank(startTime), "create_time", startTime);
		 wrapper.le(StringUtils.isNotBlank(endTime), "create_time", endTime);
		 wrapper.groupBy("month");
		 List<Map<String, Object>> maps = tankerRegistrationService.listMaps(wrapper);
		 return Result.OK(maps);
	 }

	 @AutoLog(value = "罐车登记表-柱状图")
	 @ApiOperation(value="罐车登记表-柱状图", notes="罐车登记表-柱状图")
	 @PostMapping(value = "/reportBarNoPass")
	 public Result<?> reportBarNoPass(@RequestBody ReportDTO reportDTO) {
		 String startTime = reportDTO.getStartTime();
		 String endTime = reportDTO.getEndTime();
		 QueryWrapper<TankerRegistration> wrapper = Wrappers.query();
		 wrapper.select("CONCAT(YEAR(create_time), '-', LPAD(MONTH(create_time), 2, '0')) AS month",
				 "SUM(CASE WHEN audit_status IN (3) THEN 1 ELSE 0 END) AS noPassCount",
				 "COUNT(DISTINCT CASE WHEN audit_status IN (3) THEN plate_no END) AS noPassDistinct");
		 wrapper.ge(StringUtils.isNotBlank(startTime), "create_time", startTime);
		 wrapper.le(StringUtils.isNotBlank(endTime), "create_time", endTime);
		 wrapper.groupBy("month");
		 List<Map<String, Object>> maps = tankerRegistrationService.listMaps(wrapper);
		 return Result.OK(maps);
	 }

	 @AutoLog(value = "罐车登记表-柱状图")
	 @ApiOperation(value="罐车登记表-柱状图", notes="罐车登记表-柱状图")
	 @PostMapping(value = "/reportBarUnQualified")
	 public Result<?> reportBarUnQualified(@RequestBody ReportDTO reportDTO) {
		 String startTime = reportDTO.getStartTime();
		 String endTime = reportDTO.getEndTime();
		 QueryWrapper<TankerRegistration> wrapper = Wrappers.query();
		 wrapper.select("CONCAT(YEAR(create_time), '-', LPAD(MONTH(create_time), 2, '0')) AS month",
				 "SUM(CASE WHEN audit_status IN (9) THEN 1 ELSE 0 END) AS unQualifiedCount",
				 "COUNT(DISTINCT CASE WHEN audit_status IN (9) THEN plate_no END) AS unQualifiedDistinct");
		 wrapper.ge(StringUtils.isNotBlank(startTime), "create_time", startTime);
		 wrapper.le(StringUtils.isNotBlank(endTime), "create_time", endTime);
		 wrapper.groupBy("month");
		 List<Map<String, Object>> maps = tankerRegistrationService.listMaps(wrapper);
		 return Result.OK(maps);
	 }

	 /**
	  * 本地文件上传
	  * @param mf 文件
	  * @param bizPath  自定义路径
	  * @return
	  */
	 private String uploadLocal(MultipartFile mf,String bizPath){
		 try {
			 String ctxPath = uploadpath;
			 String fileName = null;
			 File file = new File(ctxPath + File.separator + bizPath + File.separator );
			 if (!file.exists()) {
				 file.mkdirs();// 创建文件根目录
			 }
			 String orgName = mf.getOriginalFilename();// 获取文件名
			 orgName = CommonUtils.getFileName(orgName);
			 if(orgName.indexOf(".")!=-1){
				 fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
			 }else{
				 fileName = orgName+ "_" + System.currentTimeMillis();
			 }
			 String savePath = file.getPath() + File.separator + fileName;
			 File savefile = new File(savePath);
			 FileCopyUtils.copy(mf.getBytes(), savefile);
			 String dbpath = null;
			 if(oConvertUtils.isNotEmpty(bizPath)){
				 dbpath = bizPath + File.separator + fileName;
			 }else{
				 dbpath = fileName;
			 }
			 if (dbpath.contains("\\")) {
				 dbpath = dbpath.replace("\\", "/");
			 }
			 return dbpath;
		 } catch (IOException e) {
			 log.error(e.getMessage(), e);
		 }
		 return "";
	 }

	@AutoLog(value = "油罐车-存数据")
	@ApiOperation(value = "油罐车-存数据", notes = "油罐车-存数据")
	@GetMapping(value = "/m/test")
	public Result<?> test(@RequestParam(name = "start") String start,
						  @RequestParam(name = "end") String end) {
		String baseUrl = "http://39.105.40.67:8999/jeecg-boot/tankerRegistration/tankerRegistration/m/all";
		String url = baseUrl + "?start=" + start + "&end=" + end;
		JSONObject jsonObject = RestUtil.get(url);
		JSONArray result = jsonObject.getJSONArray("result");
		List<TankerRegistration> javaList = result.toJavaList(TankerRegistration.class);
//        log.info("list:{}", javaList);
        log.info("size:{}", javaList.size());
		boolean b = tankerRegistrationService.saveBatch(javaList);
		log.info("saveBatch:{}", b);
		return Result.OK();
	}

}
